package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper,Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService  setmealDishService;

    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐信息到套餐表
        save(setmealDto);

        //保存菜品和套餐的关联信息
        //获取套餐的id,关联到关联表中
        Long setmealId = setmealDto.getId();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealId));
        //批量保存到数据库
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void removeWithDish(List<Long> ids) {
        //查询套餐信息,确认是否可以删除
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId,ids);
        lqw.eq(Setmeal::getStatus,1);
        //执行查询,统计所选套餐是否处于在售状态
        int count = this.count(lqw);
        //如果count不等于0,则说明所选套餐中存在在售状态的套餐
        if(count>0){
            //抛出异常
            throw new CustomException("所选套餐中存在在售状态套餐,不可删除");
        }

        //如果可以删除,先删除setmeal表中的信息
        removeByIds(ids);

        //删除套餐菜品关联表中的菜品
        LambdaQueryWrapper<SetmealDish> SDlqw = new LambdaQueryWrapper<>();
        SDlqw.in(SetmealDish::getSetmealId,ids);
        //执行查询
        setmealDishService.remove(SDlqw);
    }
}
